package JAVAFXManyWindow.init;

import JAVAFXManyWindow.impl.infodata;

import java.io.*;
import java.net.*;

class TcpDat {
    private ServerSocket serverSocket = null;
    public void serverTcp(String httpServerAddress, int port, infodata data){
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    synchronized (TcpDat.class){
                        serverSocket = new ServerSocket();
                        SocketAddress socketAddress = new InetSocketAddress(httpServerAddress, port);
                        serverSocket.bind(socketAddress);
                        while (true){
                            Socket recvSocket = serverSocket.accept();
                            serverAppect(recvSocket,data);
                            continue;
                        }

                    }
                }catch (Exception e){e.printStackTrace();}
            }
        });
        thread.start();
    }

    private void serverAppect(Socket recvSocket,infodata data) {
        try {
            ServerRecv(URLDecoder.decode(new String(readInputStream(recvSocket.getInputStream())),"utf-8").trim(),recvSocket,data);
        }catch (Exception e){}
    }

    private void ServerRecv(String s,Socket recvSocket,infodata data)throws Exception {
        OutputStream outputStream = recvSocket.getOutputStream();
        InputStream inputStream = recvSocket.getInputStream();
        data.dat(s,inputStream,outputStream);
        recvSocket.close();
    }
    /**
     * 完整不漏数据
     * */
    private byte[] readStream(InputStream inStream) throws Exception {
        try {
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream( 5 * 1024 * 1024);
            byte[] buffer = new byte[inStream.available()];
            int len = -1;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            return outSteam.toByteArray();
        }catch (Exception e){}
        return null;
    }
    /**
     * 完整不漏数据
     * */
    private String readInputStream(InputStream inputStream) throws IOException {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 5 * 1024 * 1024);
        try {
            String str = "";
            int item = bufferedInputStream.read();
            if (item == -1) {
                return null;
            } else {
                str = str + "" + (char)item;
                int len = bufferedInputStream.available();
                if (len > 0) {
                    byte[] dats = new byte[len];
                    bufferedInputStream.read(dats);
                    str = str + new String(dats,"UTF-8");
                }
                return str;
            }
        }catch (Exception e){e.printStackTrace();}
        return null;
    }
}
